package com.imooc.miaosha.controller.FeController;

import com.alibaba.fastjson.TypeReference;
import com.imooc.miaosha.common.Const;
import com.imooc.miaosha.dto.UserDTO;
import com.imooc.miaosha.service.PayService;
import com.imooc.miaosha.util.CookieUtil;
import com.imooc.miaosha.util.JedisUtil;
import com.imooc.miaosha.util.JsonData;
import com.imooc.miaosha.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;

@Slf4j
@Controller
@RequestMapping("pay")
public class PayController {
    @Autowired
    PayService payService;

    @RequestMapping("generatePayQrCode")
    @ResponseBody
    public JsonData generatePayQrCode(Long orderId, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        String loginToken = CookieUtil.readCookie(request);
        String userJson = JedisUtil.get(Const.LOGIN_TOKEN_PREFIX, loginToken);
        UserDTO userDTO = JsonUtil.String2Obj(userJson, new TypeReference<UserDTO>() {
        });
        log.info("orderId={}===", orderId);
        if (userDTO == null) {
            return JsonData.fail("用户未登录,请登录之后再进行付款");
        }
        return payService.GeneratePay(orderId, userDTO.getId());
    }
    @RequestMapping("payCheck")
    @ResponseBody
    public JsonData check(Long orderId,HttpServletRequest request){
        String loginToken=CookieUtil.readCookie(request);
        String userJson=JedisUtil.get(Const.LOGIN_TOKEN_PREFIX,loginToken);
        UserDTO userDTO=JsonUtil.String2Obj(userJson,new TypeReference<UserDTO>(){});
        if (userDTO==null){
            return JsonData.fail("用户未登录,请登录之后再进行付款");
        }
      return   payService.checkPay(orderId,userDTO.getId());
    }

}
